//与账单相关的接口
var express = require('express');
const jwt = require('jsonwebtoken');

//用于字符串转换为时间
var moment = require('moment')

var router = express.Router();

const shortid = require('shortid');
const AccountModel = require('../../models/AccountModel');


//声明一个中间件
let checkTokenMiddleware = require('../../midwares/api/checkTokenWare')
/**
 * 列表展示
 */
router.get('/account', checkTokenMiddleware,function (req, res, next) {
 
    console.log(req.user)
    //读取集合的信息  res.render('list',{accounts:accounts,moment:moment});
    AccountModel.find().sort({ time: -1 }).exec()
      .then((accounts) => {
        res.json({
          code: '0000',
          msg: "读取成功",
          data: accounts
        })
      })
      .catch((err) => {
        res.json({
          code: '1001',
          msg: "读取失败",
          data: null
        })
      })
  
});

/**
 * 获取单个账单记录
 */
router.get('/account/:id',checkTokenMiddleware, (req, res) => {
  let { id } = req.params;
  AccountModel.findById(id).exec()
    .then((data) => {
      res.json({
        code: '0000',
        msg: "读取成功",
        data: data
      })
    })
    .catch((err) => {
      res.json({
        code: '1001',
        msg: "读取失败",
        data: null
      })
    })

})

/**
 * 添加账单记录+跳转页面
 */
router.post('/account',checkTokenMiddleware, function (req, res) {
  //插入数据库
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  })
    .then((data) => {
      res.json({
        code: '0000',
        msg: "添加成功",
        data: data
      })
    })
    .catch((err) => {
      res.json({
        code: '1001',
        msg: "读取失败",
        data: null
      })
    });



});
/**
 * 删除账单记录根据id
 */
router.delete('/account/:id',checkTokenMiddleware, (req, res) => {
  //获取params的id参数
  let id = req.params.id;
  AccountModel.deleteOne({ _id: id })
    .then(() => {
      res.json({
        code: '0000',
        msg: "删除成功",
        data: {}
      })
    })
    .catch(() => {
      res.json({
        code: '1001',
        msg: "删除失败",
        data: null
      })
    })
});

/**
 * 更新单个账单信息
 */
router.patch('/account/:id', (req, res) => {
  let { id } = req.params;
  AccountModel.updateOne({ _id: id }, req.body)
    .then(() => {
      AccountModel.findById(id).then((data) => {
        res.json({
          code: '0000',
          msg: "修改成功",
          data: data
        })
      })
    })
    .catch((err) => {
      res.json({
        code: '1001',
        msg: "修改失败",
        data: null
      })
    });
})

module.exports = router;
